﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace IndyMosaic.Models.Web.HttpHandlers
{
    public class BinaryResourceHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            Guid resourceID = Guid.Parse(context.Request.QueryString["id"]);
            BinaryResourceRepository repository = new BinaryResourceRepository();

            BinaryResource br = repository.FindById(resourceID);

            if (br != null)
            {
                context.Response.Clear();
                context.Response.AddHeader("Content-Disposition", "attachment; filename=" + br.FileName);
                context.Response.AddHeader("Content-Length", br.Binary.Length.ToString());
                context.Response.ContentType = br.ContentType.ToString();
                
                byte[] binary = br.Binary.ToArray();
                context.Response.OutputStream.Write(binary, 0, binary.Length);
                context.ApplicationInstance.CompleteRequest();
                context.Response.End();
                
            }
        }

        #endregion
    }
}
